<template>
  <div>
    <el-row type="flex">
      <div id="container"></div>
      <el-tabs v-model="activeName" @tab-click="handleClick" class="poi-list">
        <el-tab-pane label="风景" name="first" id="fjtab" class="tab-pane">
        </el-tab-pane>
        <el-tab-pane label="交通" name="second" id="jttab" class="tab-pane">
        </el-tab-pane>
      </el-tabs>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      hotel: {},

      activeName: "first",
      map: {},
      cpoint: [],
      markerList: {},
      markerData: [],
      markerListID: "",
    };
  },

  mounted() {
    this.$axios({
      url: "/hotels",
      params: {
        id: this.$route.query.id,
      },
    }).then((res) => {
      console.log(res);
      this.hotel = res.data.data[0];
      this.loadMap();
      this.markerListID = "fjtab";
      this.loadMapData("风景名胜");
    });
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
      this.markerList.clearData();
      this.map.clearMap();
      this.markerListID = tab.$attrs.id;
      if (tab.$attrs.id == "fjtab") {
        this.loadMapData("风景名胜");
      } else if (tab.$attrs.id == "jttab") {
        this.loadMapData("交通设施服务");
      }
    },

    //加载地图
    loadMap() {
      // 设置中心点坐标
      let cpoint = [
        this.hotel.location.longitude,
        this.hotel.location.latitude,
      ];
      //中心点坐标
      this.cpoint = cpoint;
      // console.log(this.cpoint)
      // 创建地图实例
      let map = new AMap.Map("container", {
        zoom: 15, //放大级别
        center: cpoint, //中心点坐标
        // viewMode:'3D', //使用3D视图
        //启用附近相关交通等等信息
        features: ["bg", "road", "building", "point"],
      });
      this.map = map;
      console.log(this.map);
      // 同时引入工具条插件，比例尺插件
      AMap.plugin(["AMap.ToolBar", "AMap.Scale"], () => {
        // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
        map.addControl(
          new AMap.ToolBar({
            direction: false,
          })
        );
        // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
        map.addControl(new AMap.Scale());
      });
      this.loadUI();
    },
    // 加载地图数据
    loadMapData(type) {
      // 添加本身酒店标记点到地图当中-当前标记
      this.map.add(
        new AMap.Marker({
          // 地理位置经纬度
          position: this.cpoint,
        })
      );

      // 查找附信息
      AMap.service(["AMap.PlaceSearch"], () => {
        //构造地点查询类
        let placeSearch = new AMap.PlaceSearch({
          type: type, // 兴趣点类别
          pageSize: 999, // 单页显示结果条数
          pageIndex: 1, // 页码
          // city: "010", // 兴趣点城市
          // citylimit: true, //是否强制限制在设置的城市内搜索
          map: this.map, // 展现结果的地图实例
          // panel: "fjtab", // 结果列表将在此容器中进行展示。
          autoFitView: false, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
          renderStyle: "default", //样式
        });
        placeSearch.searchNearBy("", this.cpoint, 1000, (status, result) => {
          // 获取结果列表保存
          this.markerData = result.poiList.pois;
          // 加载ui地图控件。实现列表地图联动
          this.loadUI();
        });
      });
    },
    // 加载地图ui库
    loadUI() {
      AMapUI.loadUI(
        ["misc/MarkerList", "overlay/SimpleMarker", "overlay/SimpleInfoWindow"],
        (MarkerList, SimpleMarker, SimpleInfoWindow) => {
          let defaultIconStyle = "blue", //默认的图标样式
            hoverIconStyle = "green", //鼠标hover时的样式
            selectedIconStyle = "purple"; //选中时的图标样式
          let markerList = new MarkerList({
            map: this.map,
            //ListElement对应的父节点或者ID
            listContainer: this.markerListID, //document.getElementById("myList"),
            //选中后显示

            //从数据中读取位置, 返回lngLat
            getPosition: function (item) {
              return [item.location.lng, item.location.lat];
            },
            //数据ID，如果不提供，默认使用数组索引，即index
            getDataId: function (item, index) {
              return item.id;
            },
            getInfoWindow: function (data, context, recycledInfoWindow) {
              if (recycledInfoWindow) {
                recycledInfoWindow.setInfoTitle(data.name);
                recycledInfoWindow.setInfoBody(data.address);

                return recycledInfoWindow;
              }

              return new SimpleInfoWindow({
                infoTitle: data.name,
                infoBody: data.address,
                offset: new AMap.Pixel(0, -37),
              });
            },
            //构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
            getMarker: function (data, context, recycledMarker) {
              let label = context.index + 1;

              if (recycledMarker) {
                recycledMarker.setIconLabel(label);
                return;
              }

              return new SimpleMarker({
                iconStyle: "blue",
                iconLabel: label,
              });
            },

            //构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
            getListElement: (dataItem, context, recycledListElement) => {
              let label = context.index + 1;
              let local = [dataItem.location.R, dataItem.location.Q];
              let dis =
                Math.round(
                  AMap.GeometryUtil.distance(this.cpoint, local) * 10
                ) / 10;
              //使用模板创建
              let innerHTML = MarkerList.utils.template(
                `   <div class="poi-item">
                        <div class="left"><%- data.name %></div>
                        <div class="right"> <%- dis %>m</div>
                    </div>`,
                {
                  data: dataItem,
                  label: label,
                  dis: dis,
                }
              );

              if (recycledListElement) {
                recycledListElement.innerHTML = innerHTML;
                return recycledListElement;
              }

              return '<li class="poibox">' + innerHTML + "</li>";
            },

            //列表节点上监听的事件
            listElementEvents: ["mouseenter", "mouseleave"],
            //marker上监听的事件
            markerEvents: ["mouseover", "mouseout"],
            //makeSelectedEvents:false,
            selectedClassNames: "selected",
            autoSetFitView: false,
          });

          window.markerList = markerList;

          markerList.on("selectedChanged", function (event, info) {
            // checkBtnStats();

            if (info.selected) {
              //   console.log(info);

              if (info.selected.marker) {
                //更新为选中样式
                info.selected.marker.setIconStyle(selectedIconStyle);
              }

              //选中并非由列表节点上的事件触发，将关联的列表节点移动到视野内
              if (!info.sourceEventInfo.isListElementEvent) {
                if (info.selected.listElement) {
                  scrollListElementIntoView($(info.selected.listElement));
                }
              }
            }

            if (info.unSelected && info.unSelected.marker) {
              //更新为默认样式
              info.unSelected.marker.setIconStyle(defaultIconStyle);
            }
          });

          markerList.on(
            "listElementMouseenter markerMouseover",
            (event, record) => {
              //   console.log(event, record);
              if (record && record.marker) {
                this.forcusMarker(record.marker);

                // console.log(record);
                //非选中的id
                if (!markerList.isSelectedDataId(record.id)) {
                  //设置为hover样式
                  record.marker.setIconStyle(hoverIconStyle);
                  //this.closeInfoWindow();
                }
              }
            }
          );
          markerList.on("listElementMouseenter markerMouseover", function (
            event,
            record
          ) {
            //   console.log(event, record);
            if (record && record.marker) {
              this.openInfoWindowOnRecord(record);
            }
          });

          markerList.on("listElementMouseleave markerMouseout", function (
            event,
            record
          ) {
            if (record && record.marker) {
              if (!markerList.isSelectedDataId(record.id)) {
                //恢复默认样式
                record.marker.setIconStyle(defaultIconStyle);
              }
            }
          });

          //数据输出完成
          markerList.on("renderComplete", function (event, records) {});

          // markerList.on('*', function(type, event, res) {
          //     console.log(type, event, res);
          // });
          //渲染数据
          this.markerList = markerList;
          markerList.render(this.markerData);
        }
      );
    },
    forcusMarker(marker) {
      marker.setTop(true);
      // console.log(marker)
      // console.log(this.map)
      this.map.setCenter(marker.getPosition());
      //不在地图视野内
      // if (!(this.map.getBounds().contains(marker.getPosition()))) {
      //     //移动到中心

      // }
    },
  },
};
</script>
<style lang="less" scoped>
#container {
  width: 650px;
  height: 360px;
}
.poi-list {
  width: 350px;
  height: 360px;
  padding-left: 20px;
  /deep/.poi-item {
    display: flex;
    height: 40px;
    color: #666;
    font-size: 14px;
    justify-content: space-between;
    padding: 0 10px;
    align-items: center;
    cursor: pointer;
  }
  .tab-pane {
    overflow: auto;
    height: 305px;
  }
}
</style>
